<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>

        <template #right>
          <el-button
            v-checkPermission="'p-em-excel-upload'"
            type="warning"
            size="small"
            @click="$router.push({ path: '/import/index?type=user' })"
          >excel导入</el-button>
          <el-button
            v-if="checkPermission('p-em-excel-export')"
            type="danger"
            size="small"
            @click="exportExcel"
          >excel导出</el-button>
          <el-button
            v-if="checkPermission('p-em-add')"
            type="primary"
            size="small"
            @click="addEmployeeFn"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card v-loading="isLoading" style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column
            label="序号"
            type="index"
            width="80"
            :index="indexMethod"
          />
          <el-table-column label="员工头像">
            <template #default="{row}">
              <img
                v-imgerror="defaultImg1"
                :src="row.staffPhoto||defaultImg"
                style="width:70px;height:70px;display:block;margin:0 auto;border-radius:50%"
                @click="showCodeDialogFn(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="formateFn"
          />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{ row }">
              {{ formateTimeFn(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                v-if="checkPermission('p-em-look')"
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >修改</el-button>
              <el-button
                v-if="checkPermission('p-em-assign-role')"
                type="text"
                size="small"
                @click="showAssignRoleDialog(row.id)"
              >
                分配角色</el-button>
              <el-button
                v-if="checkPermission('p-em-delete')"
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div
          style="
            height: 60px;
            margin-top: 10px;
            display: flex;
            justify-content: flex-end;
          "
        >
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="size"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <addEmployee :show-dialog.sync="showDialog" />
      <el-dialog title="二维码" :visible="showCodeDialog" :close-on-click-modal="false" @close="closeCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <assignRole :user-id="curUserId" :show-assign-role.sync="showAssignRole" />
    </div>
  </div>
</template>

<script>
import { getEmployeesListApi, delEmployeesByIdApi } from '@/api/empolyees'
import addEmployee from './components/add-employee.vue'
import assignRole from './components/assign-role.vue'
import enumObj from '@/constant/employees'
import dayjs from 'dayjs'
import QrCode from 'qrcode'
import { mapGetters } from 'vuex'
import mixins from '@/mixins'
import checkPermission from '@/mixins/checkPermission'

export default {
  name: 'Employees',
  components: {
    addEmployee,
    assignRole
  },
  mixins: [mixins, checkPermission],
  data() {
    return {
      page: 1,
      size: 10,
      list: [],
      total: 0,
      isLoading: false,
      showDialog: false,
      defaultImg: 'https://img2.baidu.com/it/u=2203692359,101708973&fm=253&fmt=auto&app=138&f=PNG?w=401&h=401',
      defaultImg1: 'https://img0.baidu.com/it/u=1449421639,3652262858&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400',
      showCodeDialog: false,
      curUserId: '',
      showAssignRole: false,
      tempValue: '组件中的数据'
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    showAssignRoleDialog(id) {
      this.curUserId = id
      this.showAssignRole = true
    },
    /**
     * 显示二维码弹框
     */
    showCodeDialogFn(url) {
      if (!url) {
        return
      }
      this.showCodeDialog = true
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    closeCodeDialog() {
      this.showCodeDialog = false
    },
    /**
     * 获取员工列表
     */
    async getEmployeesList() {
      this.isLoading = true
      const {
        data: { rows, total }
      } = await getEmployeesListApi(this.page, this.size)
      this.total = total
      this.list = rows
      this.isLoading = false
    },
    /**
     * 点击页码时触发
     * val 点击的那个页码
     */
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeesList()
    },
    /**
     * 计算序号
     */
    indexMethod(index) {
      // 计算方式：当前页之前所有的数据+ index+1
      return (this.page - 1) * this.size + index + 1
    },
    /**
     * 处理聘用形式
     */
    formateFn(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      // 正式、非正式、钟点工、临时工、实习生、清洁工
      // if(){ 正式}
      // if(){ 非正式}
      // if(){ 钟点工}
      // if(){ 临时工}
      // 应该封装枚举对象
      const hireType = enumObj.hireType
      const obj = hireType.find((item) => item.id === Number(cellValue))
      return obj ? obj.value : '未知'
    },
    formateTimeFn(time) {
      // 处理成 年-月-日 并且返回
      return dayjs(time).format('YYYY-MM-DD')
    },
    delEmployee(id) {
      this.$confirm('亲！确认要删除该员工吗?', '温馨提示')
        .then(async() => {
          await delEmployeesByIdApi(id)
          this.$message.success('删除成功')
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          this.getEmployeesList()
        })
        .catch(() => {})
    },
    /**
     * 点击了添加按钮
     */
    addEmployeeFn() {
      this.showDialog = true
    },
    /**
     * 导出excel
     */
    async exportExcel() {
      const {
        data: { rows }
      } = await getEmployeesListApi(1, this.total)
      const headersArr = [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const list = this.getExportData(rows, headersArr, headersRelations)
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      // import xxx from '@/vendor/Export2Excel'
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          // 导出excel的表头
          header: headersArr,
          // data 是放的excel中的数据 是一个二维数组
          // 二维数组中每一个小数组 对应的都是excel中每一行的数据
          data: list,
          // 导出的文件名
          filename: '员工信息',
          // 宽度是否自适应
          autoWidth: true,
          // 文件的后缀名
          bookType: 'xlsx',
          multiHeader,
          merges
        })
      })
    },
    getExportData(rows, headersArr, headersRelations) {
      const list = []
      rows.forEach((item) => {
        // item 就是数组中每一项
        // 接下来从item中取数据，这个数据是按headersArr 这个顺序来取得
        const tempArr = []
        headersArr.forEach((val) => {
          // val就是['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']这个数组中的每一项
          // 先从item中取数据，取出数据后 往tempArr中push
          const englishKey = headersRelations[val]
          let value = item[englishKey]
          if (englishKey === 'formOfEmployment') {
            // value  是咱们想要的吗？
            const hireType = enumObj.hireType
            const obj = hireType.find(item => item.id === +value)
            value = obj ? obj.value : '未知'
          }
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            // value 也不是咱们想要的
            value = value ? this.formateTimeFn(value) : ''
          }
          tempArr.push(value)
        })
        list.push(tempArr)
      })
      return list
    }
  }
}
</script>

<style>
</style>
